package com.heima.admin.service.Impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vos.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Service
@Slf4j
public class AdUserServiceImpl extends ServiceImpl <AdUserMapper, AdUser>implements AdUserService {


    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult login(AdUserDto dto) {
        //检查参数（用户名，密码）
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"用户名或密码不能为空");
        }
        //根据用户名查用户
        AdUser user = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }
        //判断输入密码和数据库的密码是否一致
        String inputPwd = DigestUtils.md5DigestAsHex((dto.getPassword() + user.getSalt()).getBytes());
        if (!inputPwd.equals(user.getPassword())) {
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //判断用户状态是否为9（正常）
        if (user.getStatus().intValue() == 0) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"状态异常");
        }
        //更新最后登录时间
        user.setLoginTime(new Date());
        updateById(user);
        //生成token，封装返回结果{user:用户信息    token： 令牌凭证}
        String token = AppJwtUtil.getToken(Long.valueOf(user.getId()));

        AdUserVO adUserVO = new AdUserVO();
        BeanUtils.copyProperties(user,adUserVO);//属性拷贝

        Map result = new HashMap<>();
        result.put("user",adUserVO);
        result.put("token",token);
        return ResponseResult.okResult(result);
    }
}
